package com.wandian.cqcsk.mvvm.welcome;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.google.gson.JsonObject;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.AppOpenBean;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.data.TTBaseAppApi;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.wandian.cqcsk.data.BaseAppApi;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.AppSPKeyConfig.APP_CHANNEL;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_DOWNLOAD_URL;
import static com.mylib.libcore.config.AppSPKeyConfig.INVITE_CODE_RUL; 
import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;

/**
 * @author Administrator
 * @date 2019/12/18-16:11
 * @description WelcomeActivityViewModel
 **/
public class WelcomeActivityViewModel extends BaseViewModel{
    private BaseAppApi baseAppApi;
    private TTBaseAppApi baseAppApiTT;
    public String formText="";
    public WelcomeActivityViewModel(@NonNull Application application) {
        super(application);
        baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
        baseAppApiTT =  RetrofitUtil.getTouTiaoRetrofit().create(TTBaseAppApi.class);
    }

    public MutableLiveData<AppOpenBean> appOpenBean = new MutableLiveData<>();

    public void getVersion(int version_number){
        //设置App分享url
        AppContext.getInstance().getAppPreferenceForever().setKeyValue(INVITE_CODE_RUL, "http://www.cqcsk.cn/app.html");
        showDialog();
        JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("channel", AppContext.getInstance().getAppPreferencesHelper().getKeyValue(APP_CHANNEL));
        hashMap.put("v", version_number+"");
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        String key = AESUtils.getInstance().encrypt(hashMap);
        //  String key2 = RC4Util.encry(JsonUtil.toJson(hashMap));
        Log.d("crc_aeskey",key);
        Log.d("crc_aeskey_dec",AESUtils.getInstance().decrypt(key));
        //   Log.d("crc_rc4key_dec",RC4Util.decry(key2));

        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.getVersion(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("getVersionFirst", AppUtils.getAppVersionName()+"=>"+ JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            try {
                                if(!UIUtils.isEmpty(bean.getData())){
                                    Log.d("crc_rc4key_getVersion", AESUtils.getInstance().decrypt(bean.getData()));
                                    AppOpenBean appInfoDataBean = JsonUtil.parseJsonToBean(AESUtils.getInstance().decrypt(bean.getData()),AppOpenBean.class);
                                    if(!UIUtils.isEmpty(appInfoDataBean)){
                                        AppContext.getInstance().getAppPreferenceForever().setNewsDetailsKeyID(appInfoDataBean.getNewsKey()+"");
                                        AppContext.getInstance().getAppPreferenceForever().setKeyValue(INVITE_CODE_RUL, "http://www.cqcsk.cn/app.html");
                                        AppContext.getInstance().getAppPreferenceForever().setKeyValue(APP_DOWNLOAD_URL,appInfoDataBean.getApkUrl()+"");
                                        if(!UIUtils.isEmpty(appInfoDataBean.getNewsKey())) AppContext.getInstance().getAppPreferenceForever().setNewsKey("4426eebb12da7fc1bac6a538328f6264");
                                        appOpenBean.setValue(appInfoDataBean);
                                    }else {
                                        goToMain();
                                    }
                                }else {
                                    goToMain();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                goToMain();
                            }
                        }else{
                            goToMain();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        Log.d("crc_rc4key_getVersion", JsonUtil.toJson(e)+"");
                        if(!UIUtils.isEmpty(e.getMessage())){
                            ToastUtil.show(e.getMessage());
                        }
                        goToMain();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void goToMain(){
        AppContext.getInstance().getAppPreferenceForever().setKeyValue(INVITE_CODE_RUL,"https://wandian-bk.oss-cn-beijing.aliyuncs.com/apk/app-wandian-gw.apk");
        AppContext.getInstance().getAppPreferenceForever().setKeyValue(APP_DOWNLOAD_URL, "https://wandian-bk.oss-cn-beijing.aliyuncs.com/apk/app-wandian-gw.apk");
         if(UIUtils.isLogin()){
            ARouter.getInstance().build(RouterConfig.ROUTER_MAIN).navigation();
        }else{
            ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_LOGIN).navigation();
        }
        finish();
    }

//    //获取音乐sign
//    public void getMusicSign(){
//
//        //创建Retrofit对象
//        Retrofit retrofit = RetrofitUtil.createMusicDJRetrofit();
//        //创建网络请求接口实例
//        BaseAppApi request = retrofit.create(BaseAppApi.class);
//        HashMap<String, String> hashMap = new HashMap<>();
//        //其他参数
//        hashMap.put("app-id","10002");
//        hashMap.put("app-secret","15A2730157F583C5421050A322E651C0");
//        hashMap.put("device-version","5.1.7");
//        Call<Object> call = request.gateMusicSign(hashMap);
//        //发送网络请求(异步)
//        call.enqueue(new Callback<Object>() {
//            @Override
//            public void onResponse(Call<Object> call, Response<Object> response) {
//
//                if(UIUtils.isEmpty(response.body())){
//                    return;
//                }
//                Log.d("gateMusicSign", "gateMusicSign="+ JsonUtil.toJson(response.body()));
//                if(UIUtils.isEmpty(response.body())){
//                    return;
//                }
//                MusicSignBean bean = (MusicSignBean) JsonUtil.parseJsonToBean(JsonUtil.toJson(response.body()),MusicSignBean.class);
//                if(!UIUtils.isEmpty(bean) && !UIUtils.isEmpty(bean.getData()) && !UIUtils.isEmpty(bean.getData().getPwdSign())){
//                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("music_sign",bean.getData().getPwdSign()+"");
//                    TokenSignUtils.getSignCode(new HashMap<>(),bean.getData().getPwdSign());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<Object> call, Throwable t) {
//                Log.d("gateMusicSign", "error="+t.getMessage());
//            }
//        });
//
//    }

}
